<?php
namespace App\HttpController;
use EasySwoole\EasySwoole\Swoole\Task\TaskManager;
use think\Db;
use EasySwoole\Validate\Validate;
use App\Lib\Redis\Redis;
use App\Model\User as UserModel;
use App\Model\FriendGroup as FriendGroupModel;
use App\Model\GroupMember as GroupMemberModel;
use EasySwoole\VerifyCode\Conf;
use App\Lib\Upload\Image;
use App\HttpController\Base;
class User extends Base{

    /**
     *  初始化用户信息
     */
    public function userinfo()
    {
        $token =  $this->params['token'];


        $user = Redis::getInstance()->get('User_token_'.$token);

        if (!$user) {
            return $this->writeJson(10001,"获取用户信息失败");
        }

        $user = json_decode($user,true);
        //我的群（我是群主）
        $groups = Db::table('group_member')->alias(['group_member'=>'gm','group'=>'g'])->join('group','g.id=gm.group_id')->where('gm.user_id','eq',$user['id'])->field('g.id,g.groupname,g.avatar')->select();
        foreach ($groups as $k=>$v) {
            $groups[$k]['groupname'] = $v['groupname'].'('.$v['id'].')';
        }
        //朋友的群（我是成员）
        $friend_groups = Db::table('friend_group')->where('user_id','eq',$user['id'])->field('id,groupname')->select();
        foreach ($friend_groups as $k => $v) {
            $friend_groups[$k]['list'] = Db::table('friend')
                ->alias(['friend'=>'f','user'=>'u'])->leftJoin('user','u.id = f.friend_id')
                ->where(['f.user_id'=>$user['id'],'f.friend_group_id'=>$v['id']])
                ->order('status desc')->field('u.nickname as username,u.id,u.avatar,u.sign,u.status')
                ->select();

        }

        $data = [
            'mine'      => [
                'username'  => $user['nickname'].'('.$user['id'].')',
                'id'        => $user['id'],
                'status'    => $user['status'],
                'sign'      => $user['sign'],
                'avatar'    => $user['avatar']
            ],
            "friend"    => $friend_groups,
            "group"     => $groups
        ];

        return $this->writeDataJson(0,$data,'success');

    }
    public function line() {
        $user_id = $this->params['id'];
        $type = $this->params['type'];
        if ($type == 'friend') {
            $user = Db::table('user')->where('id','eq',$user_id)->find();
            return $this->writeDataJson(0,$user,'success');

        }

    }
    public function update_sign() {
        $sign = $this->params['sign'];
        $user = Redis::getInstance()->get('User_token_' . $this->params['token']);
        $user = json_decode($user, true);
        if ($user == null) {
            $data = [
                "type" => "token expire"
            ];
            $this->response()->setMessage(json_encode($data));
        }
        $res = Db::table('user')->where('id','eq',$user['id'])->update(['sign'=>$sign]);
        if ($res) {
            return $this->writeDataJson(0,'','签名跟新成功');
        } else {
            return $this->writeDataJson(10001,'','签名跟新失败');
        }
    }
    /**
     *   获取群成员
     */
    public function groupMembers()
    {



        $id =  $this->params['id'];
        $list = Db::table('group_member')->alias(['group_member'=>'gm','user'=>'u'])
            ->join('user','u.id=gm.user_id')
            ->where('group_id','eq', $id)
            ->field('u.username,u.id,u.avatar,u.sign')->select();
        if (!count($list)) {
            return $this->writeDataJson(0,'',"获取群成员失败");
        }
        return $this->writeDataJson(0,['list' => $list],"");
    }
    /**
     *  查找页面
     */
    public function find()
    {


        $type = isset($this->params['type']) ?$this->params['type'] :'';
        $wd = isset($this->params['wd'])? $this->params['wd']:'';
        $user_list = [];
        $group_list = [];
        switch ($type) {
            case "user" :
                $user_list = Db::table('user')->where('id|nickname|username','like','%'.$wd.'%')->field('id,nickname,avatar')->select();
                break;
            case "group" :
                $group_list = Db::table('group')->where('id|groupname','like','%'.$wd.'%')->field('id,groupname,avatar')->select();
                break;
            default :
                break;
        }
        $this->fetch('find',
            [
                'user_list' => $user_list,
                'group_list' => $group_list,
                'type' => $type,
                'wd' => $wd
            ]
        );
    }

    /**
     * 消息盒子
     */
    public function messageBox()
    {

        $token =  $this->params['token'];


        $user = Redis::getInstance()->get('User_token_'.$token);

        if (!$user) {
            return $this->writeJson(10001,"获取用户信息失败");
        }


        $user = json_decode($user,true);

       Db::table('system_message')->where('user_id','eq',$user['id'])->update(['read' => 1]);

        $list =  Db::table('system_message')->alias(['system_message'=>'sm','user'=>'f'])
            ->join('user','f.id = sm.from_id')
            ->where('user_id','eq',$user['id'])
            ->order('id desc')
            ->field('sm.id,f.id as uid,f.avatar,f.nickname,sm.remark,sm.time,sm.type,sm.group_id,sm.status')->select();

        foreach ($list as $k => $v) {
            $list[$k]['time'] = $this->__time_tranx($v['time']);
        }

        $this->fetch('message_box',['list' => $list]);
    }

    /**
     * 添加好友
     */
    public function addFriend()
    {

        $token =  $this->params['token'];
        $id = $this->params['id'];


        $user = Redis::getInstance()->get('User_token_'.$token);

        if (!$user) {
            return $this->writeJson(10001,'',"获取用户信息失败");
        }



        $system_message = Db::table('system_message')->where('id','eq',$id)->find();
        $isFriend = Db::table('friend')->
        where(['user_id'=>$system_message['user_id'],'friend_id'=>$system_message['from_id']])
            ->find();

        if ($isFriend) {
            return $this->writeJson(10001,'','已经是好友了');
        }

        $data = [
            [
                'user_id' => $system_message['user_id'],
                'friend_id' =>$system_message['from_id'],
                'friend_group_id' => $this->params['groupid']
            ],
            [
                'user_id' =>$system_message['from_id'],
                'friend_id' => $system_message['user_id'],
                'friend_group_id' => $system_message['group_id']
            ]
        ];
        $res = Db::table('friend')->insertAll($data);
        if (!$res) {
            return $this->writeJson(10001,'','添加失败');
        }

        Db::table('system_message')->where('id','eq',$id)->update(['status' => 1]);
        $user = Db::table('user')->where('id','eq',$system_message['from_id'])->find();

        $data = [
            "type"  => "friend",
            "avatar"    => $user['avatar'],
            "username" => $user['nickname'],
            "groupid" => $this->params['groupid'],
            "id"        => $user['id'],
            "sign"    => $user['sign']
        ];

        $system_message_data = [
            'user_id'   => $system_message['from_id'],
            'from_id'   => $system_message['user_id'],
            'type'      => 1,
            'status'    => 1,
            'time'      => time()
        ];

        Db::table('system_message')->insert($system_message_data);

        return $this->writeDataJson(200,$data,'添加成功');
    }

    /**
     * 拒绝添加好友
     */
    public function refuseFriend()
    {

        $id = $this->params['id'];

        $system_message = Db::table('system_message')->where('id','eq',$id)->find();
        $isFriend = Db::table('friend')->
        where(['user_id'=>$system_message['user_id'],'friend_id'=>$system_message['from_id']])
            ->find();

        if ($isFriend) {
            return $this->writeDataJson(200,'','已经是好友了');
        }
        $res =  Db::table('system_message')->where('id','eq',$id)->update(['status' => 2]);

        $data = [
            'user_id'   => $system_message['from_id'],
            'from_id'   => $system_message['user_id'],
            'type'      => 1,
            'status'    => 2,
            'time'      => time()
        ];
        $res1 = Db::table('system_message')->insert($data);

        if ($res && $res1){
            return $this->writeDataJson(200,'',"已拒绝");
        } else {
            return $this->writeJson(10001,'',"操作失败");
        }
    }

    /**
     *  加入群
     */
    public function joinGroup()
    {

        $token =  $this->params['token'];


        $user = Redis::getInstance()->get('User_token_'.$token);

        if (!$user) {
            return $this->writeJson(10001,'',"获取用户信息失败");
        }
        $user = json_decode($user,true);
        $id = $this->params['groupid'];
        $isIn =Db::table('group_member')->where(['group_id'=>$id,'user_id'=>$user['id']])->find();

        if ($isIn) {
            return $this->writeJson(10001,'',"您已经是该群成员");
        }
        $group = Db::table('group')->where('id','eq',$id)->find();
        $res = Db::table('group_member')->insert(['group_id' => $id,'user_id' => $user['id']]);
        if (!$res) {
            return $this->writeJson(10001,'',"加入群失败");
        }
        $data = [
            "type" => "group",
            "avatar"    => $group['avatar'],
            "groupname" =>$group['groupname'],
            "id"        =>$group['id']
        ];
        return $this->writeDataJson(200,$data,"加入成功");
    }
    /**
     * 创建群
     */
    public function createGroup()
    {
        if($this->request()->getMethod() == 'POST'){

            $token =  $this->params['token'];


            $user = Redis::getInstance()->get('User_token_'.$token);

            if (!$user) {
                return $this->writeJson(10001,'',"获取用户信息失败");
            }

            $user = json_decode($user,true);

            $data = [
                'groupname' => $this->params['groupname'],
                'user_id'   => $user['id'],
                'avatar'    => $this->params['avatar']
            ];



            $group_id = Db::table('group')->insertGetId($data);
            $res_join = Db::table('group_member')->insert(['group_id' => $group_id,'user_id' => $user['id']]);
            if ($group_id && $res_join) {
                $data = [
                    "type" => "group",
                    "avatar"    => $this->params['avatar'],
                    "groupname" => $this->params['groupname'],
                    "id"        => $group_id
                ];
                return $this->writeDataJson(200,$data,"创建成功！");
            } else {
                return $this->writeJson(10001,'',"创建失败！");
            }
        }else{
            $this->fetch('create_group');

        }
    }

    /**
     * 聊天记录
     */
    public function chatLog()
    {
        if($this->request()->getMethod() == 'POST'){

            $token =  $this->params['token'];


            $user = Redis::getInstance()->get('User_token_'.$token);

            if (!$user) {
                return $this->writeJson(10001,'',"获取用户信息失败");
            }

            $user = json_decode($user,true);

            $id = $this->params['id'];
            $type = $this->params['type'];
            $page = $this->params['page'];

            if ($type == 'group') {
                $count = Db::table('chat_record')->alias(['chat_record'=>'cr','user'=>'u'])->join('user','u.id = cr.user_id')
                    ->where('cr.group_id','eq',$id)->count();
                $list = Db::table('chat_record')->alias(['chat_record'=>'cr','user'=>'u'])
                    ->join('user','u.id = cr.user_id')
                    ->where('cr.group_id','eq',$id)
                    ->order('time desc')
                    ->field('u.nickname as username,u.id,u.avatar,time as timestamp,cr.content')
                    ->limit(($page-1)*20,20)->select();
            } else {
                $list = Db::table('chat_record')->
                    alias(['chat_record'=>'cr','user'=>'u'])
                    ->join('user','u.id = cr.user_id')
                    ->where('cr.user_id','eq',$user['id'])
                    ->where('cr.friend_id','eq',$id)
                    ->whereOr('cr.user_id','eq',$id)
                    ->order('time desc')
                    ->field('u.nickname as username,u.id,u.avatar,time as timestamp,cr.content')
                    ->limit(($page-1)*20,20)
                    ->select();
                $count =  Db::table('chat_record')->
                alias(['chat_record'=>'cr','user'=>'u'])
                    ->join('user','u.id = cr.user_id')
                    ->where('cr.user_id','eq',$user['id'])
                    ->where('cr.friend_id','eq',$id)
                    ->whereOr('cr.user_id','eq',$id)
                    ->count();

            }
            foreach ($list as $k=>$v){
                $list[$k]['timestamp'] = $v['timestamp'] * 1000;
            }
            $list['data'] = $list;
            $list['last_page'] = ceil($count/20);
            return $this->writeDataJson(0,$list,'');
        }else{


            $id = $this->params['id'];
            $type = $this->params['type'];
            $this->fetch('chat_log',['id' => $id,'type' => $type]);

        }
    }

    /**
     * 退出登录
     */
    public function loginout()
    {
        $token =  $this->params['token'];
        Redis::getInstance()->del('User_token_'.$token);

        $this->response()->redirect("/login");

    }
}